<template>
  <div class="ygseyt">
    <h1>职位管理</h1>
    <!-- 查询（重置，搜索） -->
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float:right" type="primary" @click="onSubmit()" size="small">查询搜索</el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small"
        >重置</el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="搜索内容：">
            <el-input v-model="formInline.search" placeholder="请输入搜索的职位"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- 数据列表（新增职位） -->
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button size="mini" class="btn-add" @click="addzw" style="float:right">新增职位</el-button>
    </el-card>
    <!-- 表格数据 -->
    <div class="table-container">
      <el-table :data="currentData" border style="width: 100%" highlight-current-row>
        <el-table-column prop="jobName" label="职位"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column prop="num" label="人数"></el-table-column>
        <el-table-column prop="createBy" label="创建人"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" :formatter="dateFormatter"></el-table-column>
        <el-table-column prop="updateBy" label="更新人"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" :formatter="dateFormatter2"></el-table-column>
        <el-table-column label="操作" width="160px">
          <!-- 通过 Scoped slot 可以获取到 row, column, $index 和 store（table 内部的状态管理）的数据 -->
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        background
        hide-on-single-page
        layout="prev, pager, next"
        :total="pageNum"
        :page-size="xuanyan.pageSize"
        :pager-count="xuanyan.pageCount"
        @current-change="changePage"
        :current-page="xuanyan.currentPage"
      ></el-pagination>
    </div>
    <!-- 编辑Dialog -->
    <el-dialog
      title="编辑职位信息"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      placeholder="aaa"
    >
      <el-form
        :model="bjJobForm"
        :rules="rules"
        ref="bjJobForm"
        label-width="100px"
        class="demo-bjJobForm"
      >
        <el-form-item label="职位：" prop="jobName">
          <el-input v-model="bjJobForm.jobName"></el-input>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="bjJobForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="修改人：" prop="updateBy">
          <el-input v-model="bjJobForm.updateBy" disabled></el-input>
        </el-form-item>
        <el-form-item label="修改时间：" prop="updateTime">
          <el-input v-model="bjJobForm.updateTime" disabled></el-input>
        </el-form-item>

        <el-form-item>
          <!-- <el-button @click="resetForm('bjJobForm')">重 置</el-button> -->
          <el-button type="primary" @click="submitForm('bjJobForm')">确定修改</el-button>
          <el-button @click="closeDao">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 新增Dialog -->
    <el-dialog
      title="新增职位"
      :visible.sync="dialogVisible2"
      width="30%"
      :before-close="handleClose"
      placeholder="aaa"
    >
      <el-form
        :model="xzJobFrom"
        :rules="bjRules"
        ref="xzJobFrom"
        label-width="100px"
        class="demo-xzJobFrom"
      >
        <el-form-item label="职位：" prop="jobName">
          <el-input v-model="xzJobFrom.jobName"></el-input>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="xzJobFrom.remark"></el-input>
        </el-form-item>
        <el-form-item label="创建人：" prop="createBy">
          <el-input v-model="xzJobFrom.createBy" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="xzJobFrom.createTime" disabled></el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="resetForm('xzJobFrom')">重 置</el-button>
          <el-button type="primary" @click="submitxzForm2('xzJobFrom')">确认添加</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDao">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapActions, mapState } from "vuex";
import * as url from "../../http/api";
import axios from "../../http/http";
export default {
  name: "ygSet",
  data() {
    return {
      // 搜索
      formInline: {
        search: ""
      },
      // -------------------编辑职位
      // Dialog对话框
      dialogVisible: false,
      bjJobForm: {
        id: "",
        jobName: "",
        remark: "",
        updateBy: "",
        updateTime: ""
      },
      rules: {
        jobName: [
          { required: false, message: "请输入职位名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ]
      },
      // -------------------新增职位
      dialogVisible2: false,
      xzJobFrom: {
        jobName: "",
        remark: "",
        createBy: "",
        createTime: ""
      },
      bjRules: {
        jobName: [
          { required: true, message: "请输入职位名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "请输入职位备注", trigger: "blur" },
          { min: 2, max: 80, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ]
      },
      // 表格渲染及分页
      xuanyan: {
        currentPage: 1, //当前页
        pageSize: 8, //显示数据条数
        pageCount: 7 //页码最大显示数
      }
    };
  },
  computed: {
    // 渲染表格数据
    ...mapState({
      zwlist: function(state) {
        return state.hpStore.zwlist;
      },
      zwNum: function(state) {
        return state.hpStore.zwNum;
      }
    }),
    currentData() {
      let start = (this.xuanyan.currentPage - 1) * this.xuanyan.pageSize;
      let end = this.xuanyan.currentPage * this.xuanyan.pageSize;
      let myzwNum = this.zwNum;
      // console.log(myzwNum);
      this.zwlist.forEach(item => {
        for (let i = 0; i < myzwNum.length; i++) {
          if (item.jobName == myzwNum[i].jobName) {
            item.num = myzwNum[i].数量;
            return;
          } else {
            item.num = 0;
          }
        }
      });
      return this.zwlist.slice(start, end);
    },
    pageNum() {
      return this.zwlist.length;
    },
    // 获得登录者姓名
    ...mapGetters(["getName"])
  },
  // -------------------------------------------------------------------------------------------------
  methods: {
    ...mapActions(["ygAtherData", "upZwData"]),
    // 获取日期
    CurentTime() {
      var now = new Date();
      var year = now.getFullYear(); //年
      var month = now.getMonth() + 1; //月
      var day = now.getDate(); //日
      // var hh = now.getHours(); //时
      // var mm = now.getMinutes(); //分
      // var ss = now.getSeconds(); //秒
      var clock = year + "-";
      if (month < 10) clock += "0";
      clock += month + "-";
      if (day < 10) clock += "0";
      clock += day;
      // if (hh < 10) clock += "0";
      // clock += hh + ":";
      // if (mm < 10) clock += "0";
      // clock += mm + ":";
      // if (ss < 10) clock += "0";
      // clock += ss;
      return clock;
    },
    // -----------------------------------------------查询
    // 查询  (完成)
    onSubmit() {
      if (this.formInline.search) {
        let obj = {};
        //这里发起axios请求
        // obj.jobName = this.formInline.search;
        obj.inputValue = this.formInline.search;
        // console.log(obj);
        this.$axios({
          url: url.SELZW,
          data: obj,
          method: "post"
        }).then(res => {
          // console.log(res);
          if (res.data.length == 0) {
            this.$message({
              message: "没有该职位",
              type: "warning"
            });
          } else {
            // console.log(res.data)
            this.upZwData(res.data);
          }
        });
      } else {
        if (!this.value) {
          this.$message({
            message: "搜索内容不能为空，请重试！",
            type: "warning"
          });
        }
      }
    },
    // 查询重置  已完成
    handleResetSearch() {
      this.formInline.search = "";
      this.ygAtherData();
    },
    // 删除职位 完成
    handleDelete(index, row) {
      this.$confirm("删除后不可恢复, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let obj = {};
          obj.id = row.id;
          obj.jobName = row.jobName;
          this.$axios({
            url: url.DELZW,
            method: "post",
            data: obj
          }).then(res => {
            // console.log(res);
            if (res.data.status === "success") {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.ygAtherData();
            } else {
              this.$message({
                type: "error",
                message: "删除失败!"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // ------------------------------------------------编辑(已完成)
    handleEdit(index, row) {
      this.dialogVisible = true;
      for (let key in this.currentData[index]) {
        if (this.bjJobForm[key] != undefined) {
          this.bjJobForm[key] = this.currentData[index][key];
        }
      }
      this.bjJobForm.updateTime = this.CurentTime();
      this.bjJobForm.updateBy = this.$store.state.user.name;
    },
    // 编辑提交事件
    submitForm(formName) {
      let obj = {};
      Object.assign(obj, this.bjJobForm);
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(obj);
          axios({
            url: url.UPZW,
            method: "post",
            data: obj
          }).then(res => {
            // console.log(res);
            if (res.data.status === "success") {
              this.$message({
                type: "success",
                message: "编辑成功!"
              });
              this.closeDao();
              this.ygAtherData();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // -------------------------------------------------添加(需要提交请求接口)
    addzw() {
      this.dialogVisible2 = true;
      this.xzJobFrom.createBy = this.$store.state.user.name;
      this.xzJobFrom.createTime = this.CurentTime();
    },
    // 新增提交事件(缺少请求接口)
    submitxzForm2(formName) {
      let obj = {};
      Object.assign(obj, this.xzJobFrom);
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(obj);
          axios({
            url: url.ADDZW,
            method: "post",
            data: obj
          }).then(res => {
            if (res.data.status == "success") {
              this.$message({
                type: "success",
                message: "添加成功成功!"
              });
            }
            this.closeDao();
            this.ygAtherData();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // ----------------------------------------------------本页面公共方法
    // 更改页码
    changePage(val) {
      this.xuanyan.currentPage = val;
    },
    // 关闭Diolog 方式一
    closeDao() {
      this.dialogVisible = false;
      this.dialogVisible2 = false;
    },
    // 关闭Dialog 方式二
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    // 编辑重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    dateFormatter(row, column) {
      let datetime = row.createTime;
      if (datetime) {
        datetime = new Date(datetime);
        let y = datetime.getFullYear() + "-";
        let mon = datetime.getMonth() + 1 + "-";
        let d = datetime.getDate();
        return y + mon + d;
      }
      return "";
    },
    dateFormatter2(row, column) {
      let datetime = row.updateTime;
      if (datetime) {
        datetime = new Date(datetime);
        let y = datetime.getFullYear() + "-";
        let mon = datetime.getMonth() + 1 + "-";
        let d = datetime.getDate();
        return y + mon + d;
      }
      return "";
    }
  },
  created() {
    this.ygAtherData();
  }
};
</script>

<style scoped lang="less">
.operate-container {
  margin: 15px 0;
}
.block {
  position: absolute;
  left: 50%;
  bottom: 0%;
}
</style>